package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
)

type Disadvantage struct{}

func (*Disadvantage) CreateDisadvantage(status *admin.Disadvantage, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("无该地区信息")
	}

	status.RegionLink = account.RegionLink

	res := global.OC_DB.Where("name = ?", status.Name).Omit("id").FirstOrCreate(&status)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该状态码或者名称已存在")
	}

	return nil
}

func (*Disadvantage) EditDisadvantage(status *admin.Disadvantage) error {

	var nowDisadvantage *admin.Disadvantage

	if status.ID == 0 {
		return errors.New("无效的操作")
	}

	err := global.OC_DB.First(&nowDisadvantage, status.ID).Error

	if err != nil {
		return errors.New("找不到该状态")
	}

	err = global.OC_DB.Model(&admin.Disadvantage{}).Where("id = ?", status.ID).Updates(&admin.Disadvantage{
		Name:      status.Name,
		TextColor: status.TextColor,
		Cover:     status.Cover,
	}).Error

	if err != nil {
		return errors.New("重复的状态码或状态名称")
	}

	return nil
}

func (*Disadvantage) GetDisadvantageList(claims tools.BaseClaims) (list []*admin.Disadvantage, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	var statusList []*admin.Disadvantage

	global.OC_DB.Where("region_link LIKE ?", fmt.Sprintf("%v%%", account.RegionLink)).Find(&statusList)

	return statusList, nil
}

func (*Disadvantage) Delete(ids []int, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("该账号不存在")
	}

	var list []*admin.Disadvantage

	global.OC_DB.Find(&list, ids)

	res := utils.IsThisDisBelongThisAccount(list, account.RegionLink)

	if !res {
		return errors.New("你无权删除该排行")
	}

	global.OC_DB.Model(&admin.Disadvantage{}).Unscoped().Delete(&list)

	return nil
}

var DisadvantageService = new(Disadvantage)
